package com.daxia.bumall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.bumall.dao.SpaceDAO;
import com.daxia.bumall.dto.SpaceDTO;
import com.daxia.bumall.model.Space;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.BeanMapper;

@Service
public class SpaceService {
	
	@Autowired
	private SpaceDAO spaceDAO;
	
	public List<SpaceDTO> find(SpaceDTO query, Page page) {
		List<Space> models = spaceDAO.find(query, page);
		List<SpaceDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<SpaceDTO> findAll() {
		return this.find(new SpaceDTO(), null);
	}
	
	public List<SpaceDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new SpaceDTO(), page);
	}
	
	public Long create(SpaceDTO dto) {
		Space model = new Space();
		toModel(model, dto);
		return spaceDAO.create(model);
	}
	
	public SpaceDTO load(Long id) {
	    Space model = spaceDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(SpaceDTO dto) {
		Space model = spaceDAO.load(dto.getId());
		toModel(model, dto);
		spaceDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				throw new RuntimeException("未实现删除逻辑，请确认是物理删除还是逻辑删除");
				// spaceDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public SpaceDTO findOne(SpaceDTO query) {
		Space model = spaceDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<SpaceDTO> toDTOs(List<Space> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<SpaceDTO>(0);
		}
		List<SpaceDTO> dtos = new ArrayList<SpaceDTO>(models.size());
		for (Space model : models) {
	        SpaceDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private SpaceDTO toDTO(Space model) {
		if (model == null) {
			return null;
		}
		SpaceDTO dto = BeanMapper.map(model, SpaceDTO.class);
		
		return dto;
	}
	
	private void toModel(Space model, SpaceDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Space> toModels(List<SpaceDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Space>(0);
		}
		List<Space> models = new ArrayList<Space>(dtos.size());
		for (SpaceDTO dto : dtos) {
	        Space model = new Space();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
